package com.zy.imagineCommunity.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @Component交给spring容器去管理，每个层次都可以用
 */
@Component
public class MailClient {

    //使用指定类初始化日志对象
    private static final Logger logger = LoggerFactory.getLogger(MailClient.class);

    //邮件核心功能由spring提供，可直接注入使用
    @Autowired
    private JavaMailSender mailSender;

    //从那里发送
    @Value("${spring.mail.username}")
    private String from;

    public void sendMail(String to, String subject, String content) {
        try {
            //创建message
            MimeMessage message = mailSender.createMimeMessage();
            //帮助构建message里面的内容
            MimeMessageHelper helper = new MimeMessageHelper(message);
            //从哪里发出
            helper.setFrom(from);
            //收件人
            helper.setTo(to);
            //设置主题
            helper.setSubject(subject);
            //设置内容加true为html，不然为text
            helper.setText(content, true);
            //发送从helper里构建的邮件
            mailSender.send(helper.getMimeMessage());
        } catch (MessagingException e) {
            logger.error("发送邮件错误:" + e.getMessage());
        }
    }

}

